package top.zhongyy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import top.zhongyy.pojo.Comment;
import top.zhongyy.mapper.CommentMapper;
import top.zhongyy.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.naming.CompositeName;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Andy
 * @since 2021-03-25
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    
    @Autowired
    private CommentMapper commentMapper;
    
    //所有子评论都放到list中，返回Comment对象
    private List<Comment> tempReplies = new ArrayList<>();
    
    // 获取单条博客评论 并且只生成二级树
    @Override
    public List<Comment> getBlogComments(Long blogId) {
        // 获取该条博客下的所有顶级评论
        List<Comment> rootComments = commentMapper.getRootComments(blogId);
        return combineChildren(rootComments);
    }
    
    
    private List<Comment> combineChildren(List<Comment> comments) {
        for (Comment comment : comments) {
            // 遍历单条父级评论
            recursively(comment);
            comment.setReplyComments(tempReplies);
            tempReplies = new ArrayList<>();
        }
        return comments;
    }
    
    /**
     * @param comment 父级评论
     * @Desc: TODO
     * @author Andy
     * @date: 2021/3/27 13:51
     */
    private void recursively(Comment comment) {
        // 获取该评论的子评论 递归的时候一定要在递归头
        comment.setReplyComments(commentMapper.getChildComments(comment.getId()));
        if (comment.getReplyComments().size() > 0) {
            List<Comment> replies = comment.getReplyComments();
            for (Comment reply : replies) {
                // 这里添加的是子评论
                tempReplies.add(reply);
                recursively(reply);
            }
        }
        
    }
    
}
